package com.llh.pojo.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.IOException;

/**
 * 通用的解析post响应体类
 */
//@Log4j2
@Data
public class CommonRespTool {
    private static Logger logger = LogManager.getLogger(CommonRespTool.class);

    /**
     * 从响应模型中获取响应实体,并返回响应体的json字符串
     *
     * @param response
     * @return
     * @throws Exception
     */
    public static String convert(CloseableHttpResponse response) throws Exception {

        HttpEntity responseEntity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            logger.error("调用接口失败");
            throw new RuntimeException("调用接口失败");
        }
        if (responseEntity != null) {
            String s;
            try {
                s = EntityUtils.toString(responseEntity, "UTF-8");
                logger.info("响应体:" + s);
                return s;
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("http响应体转换成json失败");
            }

        } else {
            logger.error("http响应体为空");
            throw new Exception("http响应体为空响应体为空");

        }
    }


}
